<?php
namespace App\Http\Controllers\MobileWeb;

use App\Http\Controllers\WebController;
use App\Http\Controllers\Business\App\MyCenter\MyCenter;
use App\Http\Controllers\Business\App\PublicBusiness;
use App\Http\Controllers\Business\App\Wallet\Wallet;
use App\Http\Controllers\Business\App\Salesman\SalesmanManagement;
use App\Http\Controllers\Business\App\Statistic\StatisticManagement;
use App\Http\Controllers\Business\Common\Common;
use App\Models\AllInPay;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class WalletController extends WebController
{
    //首页
    public function index() {
        $userId = Auth::id();
        $result = Wallet::index($userId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        $data['notdoublemoney'] = $data['doublemoney'] / 2;
//        $rechargeResult = Wallet::rechargeOrderList($userId);
//        if ($rechargeResult['status'] == 'failed') {
//            $data['rechargelists'] = [];
//        } else {
//            $data['rechargelists'] = $rechargeResult['data'];
//        }
//        $orderResult = Wallet::payOrderList($userId);
//        if ($orderResult['status'] == 'failed') {
//            $data['orderlists'] = [];
//        } else {
//            $data['orderlists'] = $orderResult['data'];
//        }
        return view('mobile.wallet.index', $data);
    }
    //订单
    public function orderList() {
        $userId = Auth::id();
        if($this->request->has('commentstatus')) {
            $commentStatus = $this->request->get('commentstatus');
        } else {
            $commentStatus = '';
        }
        $result = Wallet::payOrderList($userId, $commentStatus);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        $data = $result['data'];
        return $this->responseSuccessData($data);
    }
    //评论
    public function comment() {
        $orderNumber = $this->request->get('ordernumber');
        $shopName = $this->request->get('shopname');
        $data = [
            'ordernumber' => $orderNumber,
            'shopname' => $shopName
        ];
        return view('mobile.wallet.comment', $data);
    }
    //新增评论
    public function addComment() {
        $userId = Auth::id();
        $orderNumber = $this->request->get('ordernumber');
        $score = $this->request->get('score');
        $content = $this->request->get('content');
        if($this->request->has('picture')) {
            $picture = $this->request->get('picture');
        } else {
            $picture = '';
        }
        $result = PublicBusiness::newComment($orderNumber, $userId, $score, $content, $picture);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //订单详情
    public function orderDetail() {
        $userId = Auth::id();
        $orderNumber = $this->request->get('ordernumber');
        $walletResult = Wallet::orderDetails($userId, $orderNumber);
        if($walletResult['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $walletResult['data'];
        if(!empty($data['comment'])) {
            $comment = $data['comment'];
            $picture = $comment['picture'];
            if(!empty($picture)) {
                $pictureArray = explode(',', $picture);
            } else {
                $pictureArray = [];
            }
            $comment['picture'] = $pictureArray;
            $data['comment'] = $comment;
        }
        return view('mobile.wallet.order_detail', $data);
    }
    //买单成功
    public function payEnd() {
        $userId = Auth::id();
        $orderNumber = $this->request->get('ordernumber');
        $walletResult = Wallet::orderDetails($userId, $orderNumber);
        if($walletResult['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $walletResult['data'];
        if(!empty($data['comment'])) {
            $comment = $data['comment'];
            $picture = $comment['picture'];
            if(!empty($picture)) {
                $pictureArray = explode(',', $picture);
            } else {
                $pictureArray = [];
            }
            $comment['picture'] = $pictureArray;
            $data['comment'] = $comment;
        }
        return view('mobile.wallet.pay_end', $data);
    }
    //支付
    public function pay() {
        $userId = Auth::id();
        $payResult = Wallet::getPayCode($userId);
        if($payResult['status'] == 'failed') {
            if($payResult['message'] == 'balance_not_enough') {
                //余额不足
                return view('mobile.wallet.balance_not_enough');
            } else {
                return view('errors.404');
            }
        } else {
            $data = $payResult['data'];
            if(isset($data['ordernumber'])) {
                //支付成功
                $orderNumber = $data['ordernumber'];
                $result = Wallet::orderDetails($userId, $orderNumber);
                if($result['status'] == 'failed') {
                    return view('errors.404');
                } else {
                    $data = $result['data'];
                    return view('mobile.wallet.pay_end', $data);
                }
            } elseif(isset($data['paycode'])) {
                //获取支付码
                $balanceResult = Wallet::index($userId);
                if($balanceResult['status'] == 'failed') {
                    $data['balance'] = '';
                } else {
                    $data['balance'] = $balanceResult['data']['balance'];
                }
                return view('mobile.wallet.pay_ready', $data);
            }
        }
    }
    //支付状态
    public function getPayStatus() {
        $userId = '';
        if(!$this->request->has('ordernumber')) {
            return $this->responseError('请求参数不对');
        }
        $orderNumber = $this->request->get('ordernumber');
        $result = Wallet::getPayStatus($userId, $orderNumber);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        $message = '获取信息成功';
        $data = $result['data'];
        return $this->responseSuccess($message, $data);
    }
    //买单   扫一扫或出示二维码
    public function payWay() {
        return view('mobile.wallet.pay_way');
    }
    //充值记录
    public function rechargeNote() {
        $userId = Auth::id();
        $result = Wallet::rechargeOrderList($userId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists' => $lists
        ];
        return view('mobile.wallet.recharge_note', $data);
    }
    //从商家详情中进入买单   输入金额
    public function payShopIn() {
        $shopId = $this->request->get('shopid');
        $shopName = $this->request->get('shopname');
        $address = $this->request->get('address');
        $payInfo = $this->request->get('payinfo');
        $data = [
            'shopid' => $shopId,
            'shopname' => $shopName,
            'address' => $address,
            'payinfo' => $payInfo
        ];
        return view('mobile.wallet.pay_shopin', $data);
    }
    //输入订单金额，获取最大金额的红包
    public function getRedEnvelopeMaxAmount() {
        $userId =  Auth::id();
        $money = $this->request->get('money');
        $result = Wallet::getRedEnvelopeMaxAmount($userId, $money);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        $redEnvelopeAmount = $result['data'];
        $actualAmount = $money - $redEnvelopeAmount;
        $data = [
            'orderamount' => $money,
            'redenvelopeamount' => $redEnvelopeAmount,
            'actualamount' => $actualAmount
        ];
        return $this->responseSuccessData($data);
    }
    //从商家详情中进入买单   输入金额
    public function payShopInResult() {
        $shopId = $this->request->get('shopid');
        $money = $this->request->get('money');
        $user = Auth::user();
        if(!$user) {
            return $this->responseError("获取信息失败");
        }
        $userId = $user->id;
        $payPassword = $user->paypassword;
        if($this->request->has('paypassword')) {
            $checkPayPassword = $this->request->get('paypassword');
        } else {
            $checkPayPassword = '';
        }
        if($payPassword && ($checkPayPassword == '')) {
            $data = [
                'ordernumber' => '',
                'status' => '4',
                'password' => '1',
                'shopid' => $shopId,
                'money' => $money
            ];
            return $this->responseSuccessData($data);
        } elseif($payPassword && (md5($checkPayPassword.env('PASSWORD_SALT')) != $payPassword)) {
            return $this->responseError('支付密码错误');
        }
        if(date('Y-m-d')>='2017-02-01') {
            //2017-03-01 新版本  自动领取红包功能
            $collectionMethod = 'user';
            $payCode = '';
            $shopUserId = '';
            $type = '';
            $result = Common::collectMoney($shopId,$money,$collectionMethod, $userId, $payCode, $shopUserId, $type);
            if($this->request->has('iOSorAndroid')) {
                $userAgent = $this->request->get('iOSorAndroid');
            } else {
                $userAgent = $this->request->header('user-agent');
            }
            $ip = $this->request->ip();
            StatisticManagement::addUserLoginAfterInfo($userId, 'order', $userAgent, $ip);
        } else {
            //老版本
            $result = PublicBusiness::collectMoney($userId, $shopId, $money);
        }
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessData($result['data']);
        }
    }
    //充值
    public function recharge() {
        $userId = Auth::id();
        $result = Wallet::getBalanceByUserId($userId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $balance = $result['data'];
        $data = [
            'balance' => $balance
        ];
        return view('mobile.wallet.recharge', $data);
    }
    //设置支付密码
    public function rechargePassword() {
        $type = $this->request->get('type');
        if($type == 'add') {
            $data = [
                'title' => "输入支付密码",
                'message' => '输入支付密码(6位的数字)',
                'type' => 'add'
            ];
        } else {
            $data = [
                'title' => '输入支付密码',
                'message' => '输入支付密码(6位的数字)',
                'type' => ''
            ];
        }
        return view('mobile.wallet.recharge_password', $data);
    }
    //设置从商家进入的支付密码
    public function payShopinPassword() {
        $shopId = $this->request->get('shopid');
        $money = $this->request->get('money');
        $data = [
            'shopid' => $shopId,
            'money' => $money,
        ];
        return view('mobile.wallet.pay_shopin_password', $data);
    }
    //新用户领取翻倍券页面
    public function newUserGetDoubleCoupon() {
        $userAgent = $this->request->header('user-agent');
        $mobile = $this->request->get('mobile'); //TODO 加密
        $mobile = substr($mobile, 0, 11);
        $data = [
            'useragent' => $userAgent,
            'mobile' => $mobile
        ];
        return view('mobile.wallet.new_user_double_coupon', $data);
    }
    //新用户领取翻倍券
    public function getDoubleCoupon() {
        $mobile = $this->request->get('mobile');
        //$userId = PublicBusiness::encrypt($userId, 'D', ''); //解密
        $result = Wallet::newUserDoubleCoupon($mobile);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //充值支付页面
    public function rechargePay(){
        if (!$this->request->has('amount')) {
            return view('mobile.error');
        }
        $amount = $this->request->get('amount');
        $userAgent = $this->request->header('User-agent');
        if (stripos($userAgent, 'MicroMessenger') != false) {
            $userAgent = "wx";
        } else {
            if (stripos($userAgent, 'Mobile') != false) {
                $userAgent = 'mobile';
            } else {
                $userAgent = 'pc';
            }
        }
        $data = [
            'amount' => $amount,
            'useragent' => $userAgent
        ];
        return view('mobile.wallet.recharge_pay', $data);
    }
    //充值支付
    public function rechargeStartPay() {
        $userAgent = $this->request->header('User-agent');
        $money = $this->request->get('money');
        $ip = $this->request->ip();
        $userId = Auth::id();
        StatisticManagement::addUserLoginAfterInfo($userId, 'recharge',$userAgent, $ip);
        if (stripos($userAgent, 'MicroMessenger') != false) {
            //微信支付
            $this->rechargePayByWX($money);
        } else {
            //支付宝支付
            $this->rechargePayByALiPay($money);
        }

    }
    //微信支付
    public function rechargePayByWX($money) {
        //$data = AllInPay::allinpayRecharge(Auth::id(),$money);
        $data = AllInPay::allinpayRechargeByV2Version(Auth::id(), $money);
        if($data['status']=='success') {
            $data = $data['data'];
        } else {
            echo $data['message'];
            exit;
        }
        $wxpay = <<<EOT
        <html>
        <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8" />
        <title>微信安全支付</title>
        </head>
        <body>
        <script type="text/javascript">
        function jsApiCall()
        {
            WeixinJSBridge.invoke(
                    'getBrandWCPayRequest',
                    {$data['jsApiParameters']},
                    function(res){
                        WeixinJSBridge.log(res.err_msg);
                        if(res.err_msg == "get_brand_wcpay_request:ok")
                        {
                            //alert(res.err_code+res.err_desc+res.err_msg);
                            window.location.href = '/mobile/wallet/recharge/end?ordernumber={$data['ordernumber']}';
                        }
                        else
                        {
                            window.location.href = '/mobile/wallet/recharge';
                        }
                    }
            );
        }
        function callpay()
        {
            if (typeof WeixinJSBridge == "undefined"){
                if( document.addEventListener ){
                    document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                }else if (document.attachEvent){
                    document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                    document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                }
            }else{
                jsApiCall();
            }
        }
        window.onload=callpay();
    </script>
    </body>
    </html>
EOT;
        echo $wxpay;
    }
    //支付宝支付
    public function rechargePayByALiPay($money) {
        //$data = Wallet::webReadyRecharge(Auth::id(),$money,'1');
        $data = Wallet::webReadyRechargeByV2Version(Auth::id(),$money,'1');
        if($data['status']=='success') {
            $data = $data['data'];
            if(isset($data['ordernumber'])) {
                SalesmanManagement::addUserSalesmanByRecharge(Auth::id(), $data['ordernumber'], $money);
            }
        }
        echo $data;
        exit;
    }
    //充值结束的页面
    public function rechargeEnd() {
        $userId = Auth::id();
        $rechargeNumber = $this->request->get('ordernumber');
        $result = Wallet::rechargeDetails($userId, $rechargeNumber);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        return view('mobile.wallet.recharge_end', $data);
    }
    //充值结束的页面
    public function rechargeDetails() {
        $userId = Auth::id();
        $rechargeNumber = $this->request->get('rechargenumber');
        $result = Wallet::rechargeDetails($userId, $rechargeNumber);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        return view('mobile.wallet.recharge_details', $data);
    }

    public function rechargePayByAppWX() {
        $mobile = $this->request->get('mobile');
        $money = $this->request->get('money');
        $openid = $this->request->session()->get('openid');
        if(!$openid)
        {
            $openid = Auth::user()->openid;
            if(!$openid)
            {
                echo '获取用户信息失败！';
                exit;
            }
        }
        if($money % 10 != 0 || !$money || !$mobile){
            echo '参数错误！';
            exit;
        }
        $userid = User::where('mobile',$mobile)->pluck('id')->first();
        if(!$userid)
        {
            echo '该用户不存在！';
            exit;
        }
        $data = AllInPay::allinpayRecharge($userid,$money,'2',$openid);
        if($data['status']=='success')
        {
            $data = $data['data'];
        }
        else
        {
            echo $data['message'];
            exit;
        }
        $wxpay = <<<EOT
        <html>
        <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8" />
        <title>微信安全支付</title>
        </head>
        <body>
        <script type="text/javascript">
        function jsApiCall()
        {
            WeixinJSBridge.invoke(
                    'getBrandWCPayRequest',
                    {$data['jsApiParameters']},
                    function(res){
                        WeixinJSBridge.log(res.err_msg);
                        if(res.err_msg == "get_brand_wcpay_request:ok")
                        {
                            //alert(res.err_code+res.err_desc+res.err_msg);
                            window.location.href = '/mobile/wallet/recharge/end?ordernumber={$data['ordernumber']}';
                        }
                        else
                        {
                            window.location.href = '/mobile/wallet/recharge';
                        }
                    }
            );
        }
        function callpay()
        {
            if (typeof WeixinJSBridge == "undefined"){
                if( document.addEventListener ){
                    document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                }else if (document.attachEvent){
                    document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                    document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                }
            }else{
                jsApiCall();
            }
        }
        window.onload=callpay();
    </script>
    </body>
    </html>
EOT;
        echo $wxpay;
    }
}